/**
 * 
 */
package name.pathfinder.tuberose.example.internal.services;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import name.pathfinder.tuberose.example.entities.User;
import name.pathfinder.tuberose.example.services.UserService;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


/**
 * @author yaowei
 *
 */
@Transactional
@Service("userService")
public class UserServiceImpl implements UserService {

    private static final String SEARCH_QUERY = "select u from User u where upper(u.username) like :term";

    @PersistenceContext
    private EntityManager em;
    
	/* (non-Javadoc)
	 * @see com.supcon.orchid.foundation.serivces.UserService#saveUser(com.supcon.orchid.foundation.entities.User)
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class})
	public User saveUser(User user) {
		if(null == user) throw new IllegalArgumentException("user can not be null.");
		if(null != user.getId()) {
			em.merge(user);
		} else {
			em.persist(user);
		}
		em.flush();
		return user;
	}

	/* (non-Javadoc)
	 * @see com.supcon.orchid.foundation.serivces.UserService#deleteUser(long)
	 */
	@Override
	public User deleteUser(long id) {
		User user = findUser(id);
		if(null != user) em.remove(user);
		return user;
	}

	/* (non-Javadoc)
	 * @see com.supcon.orchid.foundation.serivces.UserService#findUser(long)
	 */
	@Override
	@Transactional(propagation=Propagation.SUPPORTS)
	public User findUser(long id) {
		return em.find(User.class, id);
	}
	
}
